import {autoUpdater} from 'electron-updater'
import { ipcMain,dialog } from 'electron'
const log = require("electron-log")
log.transports.file.maxSize = 1048576;
log.transports.console.level = 'silly';
autoUpdater.logger = log
autoUpdater.logger.transports.file.level = "info"

const server = 'http://test.thago.cn:40000'
const url = `${server}/parkview`
///${process.platform}-${process.arch}${app.getVersion()} 
// 开始检查更新
ipcMain.on('checkForUpdates', () => autoUpdater.checkForUpdates())
 
// 开始下载更新
ipcMain.on('downLoadUpdate', () => autoUpdater.downloadUpdate())

let win=null;
const updateHandle = (mainWin) => {
    win=mainWin
    autoUpdater.autoDownload = false  // 手动指定下载 
    autoUpdater.setFeedURL(url)  // 更新包的地址  

    // let updaterCacheDirName = 'electron-updater1'
    // const updatePendingPath = path.join(autoUpdater.app.baseCachePath, updaterCacheDirName, 'pending')
    // log.warn(updatePendingPath)
    // fs.emptyDir(updatePendingPath)
    // log.warn(autoUpdater.app.baseCachePath)

     const statusMessage = {
        error: {status: -1, msg: '检测更新查询异常'},
        checking: {status: 0, msg: '正在检查应用程序更新'},
        updateAva: {status: 1, msg: '检测到新版本，正在下载,请稍后'},
        updateNotAva: {status: 2, msg: '您现在使用的版本为最新版本,无需更新!'},
        downloadSuccess: {status: 2, msg: '下载新版成功'}
    } 
    //执行自动更新检查
    // autoUpdater.checkForUpdates()
 
    //更新错误
    autoUpdater.on('error', error => {
        log.info(error)
        // sendUpdateMessage('uploadMessage', {payload: statusMessage.error, output: error})
    })
 
    //检查中
    autoUpdater.on('checking-for-update', v => {
        log.info('检查中')
        sendUpdateMessage('uploadMessage', {payload: statusMessage.checking, output: v})
    })
 
    //发现新版本
    autoUpdater.on('update-available', info => {
        log.info('发现新版本')
        sendUpdateMessage('uploadMessage', {payload: statusMessage.updateAva, output: info})
    })
 
    //当前版本为最新版本
    autoUpdater.on('update-not-available', info => {
        log.info('当前版本为最新版本')
        sendUpdateMessage('uploadMessage', {payload: statusMessage.updateNotAva, output: info})
    })
 
    // 更新下载进度事件
    autoUpdater.on('download-progress', progress => sendUpdateMessage('downloadProgress', progress))
 
    // 当下载完更新包后触发
    autoUpdater.on('update-downloaded', info => {
      dialog.showMessageBox({
        type: 'info',
        title: '软件更新',
        message: "发现新版本"+info.version+", 确定安装?",
        detail: process.platform === 'win32' ? info.releaseNotes : info.releaseNotes,
        buttons: ['确定', '取消']
      }).then(returnValue => {
        if (returnValue.response === 0){
          sendUpdateMessage('uploadMessage', {payload: statusMessage.downloadSuccess, output: info})
          autoUpdater.quitAndInstall()
        } 
      }) 
    })
}

//发送消息
function sendUpdateMessage(msg,text){
  win.webContents.send(msg,text);
}
 
export default updateHandle